package util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.codehaus.jackson.JsonNode;

import play.libs.Json;

public class CopyOfGenerateJsLogic {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader("conf/newRoutes"));

		String line = nextLine(br);
		while (line != null) {
			if (line.startsWith("#MODULE")) {
				writeModule(line.split("\\s+"), br);
			}
			line = nextLine(br);
		}
		br.close();

	}

	public static String nextLine(BufferedReader br) throws IOException {
		try {
			String line = br.readLine().trim();
			while (line.length() == 0)
				line = br.readLine().trim();
			return line;
		} catch (NullPointerException e) {

			return null;
		}
	}

	private static void writeModule(String desc[], BufferedReader br)
			throws IOException {

		String line = nextLine(br);
		System.out.println("trait " + desc[1] + "EP {");
		while (!line.startsWith("#ENDMODULE")) {
			if (line.startsWith("#SERVICE")) {
				writeService(line.replaceAll("#SERVICE\\s*", "").trim(), br,
						new PrintWriter(System.out));
			}
			line = nextLine(br);
		}
		System.out.println("}");

	}

	private static void writeService(String desc, BufferedReader br,
			PrintWriter pw) throws IOException {

		String desc1 = nextLine(br);
		// group 2 tiene los parametros
		Matcher m = Pattern.compile("^.*\\.(.+?)(\\((.*?)\\))$").matcher(desc1);

		if (m.matches()) {
			String x = "def " + m.group(1) + "(params:AnyRef{";
			for (String param : m.group(3).split(",")) {
				if (param.trim().length() > 0)
					x += "var " + param + ";";
			}
			JsonNode jnode = Json.parse(desc);
			x += "}";
			if (!desc1.startsWith("GET")) {
				x += ",body:" + jnode.get("bt").asText();
			}
			String rt = jnode.get("rt") == null ? "Unit" : jnode.get("rt")
					.asText();
			System.out.println(x + "):" + rt + ";");
			System.out.println(x + ",callback:" + rt + "=>Unit):" + rt + ";");
		} else {
			new Exception("Hay algo mal en las rutas en la linea que dice: "
					+ desc1);
		}

		System.out.println();
	}
}